<template>
  <BKModal
    v-model="visible"
    width="300"
    :show-zoom="false"
    :title="title"
    class="no-close map-query-modal"
    :lock-view="false"
    :lock-scroll="false"
    :mask="false"
    :resize="false"
    :draggable="true"
    :position="{
      top:188,
      left:636
    }"
  >
    <template #header>
      <div class="flex-between full-box ai-c">
        <span class="t-nowrap f-16 c-white">
          {{ title }}
        </span>
        <i
          class="el-icon-close c-pointer c-white"
          @click="$emit('close',activeId)"
        />
      </div>
    </template>
    <div
      class="map-geo-query c-white full-box flex-1"
    >
      <div
        class="flex-ai-c full-box jc-c  gap-6 query-box-bg"
        v-show="activeId === 'forcast'"
      >
        <div
          v-for="(item,index) in forcastConfig"
          :key="index"
          class="c-pointer query-type-item flex-1"
          @click="debounceRenderMapPolygons(item.dataIndex)"
          :class="{'is-active':queryDataIndex===item.dataIndex}"
        >
          <span class="query-type-label">{{ item.label }}</span>
        </div>
      </div>
      <div
        class="d-flex-c full-box query-box-bg"
        v-show="activeId === 'history'"
      >
        <el-row
          :gutter="6"
        >
          <el-col
            v-for="(item,index) in currentYearMonths"
            :key="index"
            :span="item.span"
          >
            <div
              class="c-pointer query-type-item full-width margin-b-6"
              :class="{
                'is-active':queryDataIndex===item.dataIndex,
                'disabled':item.disabled
              }"
              @click="debounceRenderMapPolygons(item.dataIndex)"
            >
              <span class="query-type-label">{{ item.label }}</span>
            </div>
          </el-col>
        </el-row>

        <div class="flex-ai-c  gap-10">
          <div
            v-for="(item,index) in historyConfis"
            :key="index"
            class="c-pointer query-type-item flex-1"
            @click="debounceRenderMapPolygons(item.dataIndex)"
            :class="{
              'is-active':queryDataIndex===item.dataIndex,
              'disabled':item.disabled
            }"
            :disabled="item.disabled"
          >
            <span class="query-type-label">{{ item.label }}</span>
          </div>
        </div>
      </div>
      <div
        class="center-time-text d-flex-c jc-c"
        v-show="curQueryTime"
        v-append
      >
        <div style="margin-bottom: 8px;">
          {{ curQueryTime }}
        </div>
        <div>
          {{ title }}实况图
        </div>
      </div>
    </div>
  </BKModal>
</template>

<script>
import { debounce } from 'throttle-debounce'
// 颜色替换
const colorKeyMap = {
  'rgb(170,255,191,1)': 'rgb(170,255,191,1)',
  'rgb(0,213,106,1)': 'rgb(0,213,106,1)',
  'rgb(0,255,255,1)': 'rgb(0,255,255,1)',
  'rgb(0,0,255,1)': 'rgb(0,0,255,1)',
  'rgb(255,128,255,1)': 'rgb(255,128,255,1)',
  'rgb(183,3,179,1)': 'rgb(183,3,179,1)'
}
export default {
  name: 'MapGeoQuery',
  props: {
    activeId: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    this.forcastConfig = [
      { label: '未来1天', dataIndex: '7', span: 8 },
      { label: '未来2天', dataIndex: '8', span: 8 },
      { label: '未来3天', dataIndex: '9', span: 8 }
    ]
    return {
      queryDataIndex: '',
      curQueryTime: ''
    }
  },
  watch: {
    activeId: {
      immediate: true,
      handler (val) {
        this.queryDataIndex = ''
        this.curQueryTime = ''
      }
    }
  },
  computed: {
    currentYearMonths () {
      const curMonth = Number(this.$utils.createDate().format('MM'))
      const result = []
      for (let i = 0; i < 12; i++) {
        const diff = curMonth - 1 - i // index从0开始
        result.push({
          label: i + 1 + '月',
          dataIndex: (i > curMonth - 1) ? '' : (i === (curMonth - 1) ? '23' : 22 - diff),
          span: 4,
          disabled: i > curMonth - 1
        })
      }
      return result
    },
    title () {
      return this.activeId === 'history' ? '历史降雨' : '预报降雨'
    },
    historyConfis () {
      const floodSeasonDisabled = Number(this.$utils.createDate().format('MM')) < 6
      return [
        { label: '今年以来', dataIndex: '22' },
        { label: '本月以来', dataIndex: '23' },
        { label: '入汛以来', dataIndex: '24', disabled: floodSeasonDisabled }
      ]
    }
  },
  created () {
    this.debounceRenderMapPolygons = debounce(300, this.renderMapPolygons)
  },
  methods: {
    async renderMapPolygons (dataIndex) {
      if (!dataIndex) return
      this.queryDataIndex = dataIndex
      const layerId = 'ysqjcdp_' + this.activeId
      const layer = await this.$mapManager.invokeUtils('getLayer', layerId)
      if (!layer) {
        console.warn('未创建对应图层' + layerId)
        return
      }
      layer.getSource().clear()
      const geoJsonData = await this.getGeoByParams()
      const resultFeature = []
      const that = this
      if (geoJsonData && geoJsonData.type === 'FeatureCollection') {
        geoJsonData.features.forEach(function (obj) {
          const feature = new window.ol.format.GeoJSON().readFeature(obj)
          const style = that.setFeaturesStyle(obj)
          feature.setStyle(style)
          resultFeature.push(feature)
        })
      }
      if (resultFeature.length === 0) {
        this.$message.warning('暂无数据')
        this.queryDataIndex = ''
        return
      }
      layer.getSource().addFeatures(resultFeature)
    },
    async  getGeoByParams () {
      const data = await this.$request.formDataPost(window.outApiHw + 'hw-api/outInterface/dataBaseResultRainList', {
        dataIndex: this.queryDataIndex
      })
      this.curQueryTime = this.formatterDate(data.btime) + ' - ' + this.formatterDate(data.etime)
      return data.polygons ?? {}
    },
    formatterDate (date) {
      return this.$utils.createDate(date).format('MM月DD日 HH时')
    },
    setFeaturesStyle (obj) {
      const fillColor = colorKeyMap[obj.properties.fillColor] ? colorKeyMap[obj.properties.fillColor] : obj.properties.fillColor
      const fill = new window.ol.style.Fill({
        color: fillColor
      })
      const option = { fill }
      return new window.ol.style.Style(option)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep.map-query-modal {
  .vxe-modal--box {
    background: transparent;
    border: 1px solid;
    border-radius: 4px;
    overflow: hidden !important;
    border-image: linear-gradient(0deg, #1263cd, #20d3f0 50%, #1263cd) 1 1;
    box-shadow: 0 0 8px 0 #00f6ff;
  }

  .vxe-modal--header {
    height: 32px;
    padding: 0 10px;
    background: linear-gradient(90deg, #0e6dd5 1%, rgba(90, 129, 249, 0) 100%);
    border-bottom: 1px solid  #20d3f0;
  }
}

.el-icon-close:hover {
  color: #00f6ff;
}

.map-geo-query {
  display: flex;
  flex-direction: column;
}

.query-box-bg {
  padding: 8px;
  background: linear-gradient(90deg, rgba(5, 47, 133, 0.7)  0%, rgba(5, 47, 133, 0.4) 100%);
}

.query-type-item {
  height: 28px;
  // padding: 7px 9px;
  font-size: 14px;
  background: rgba(21, 52, 120, 0.8);
  border: 1px solid #32bbf1;
  box-shadow: inset 0 0 2px #32bbf1;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;

  &.margin-b-6 {
    margin-bottom: 6px;
  }

  &.is-active,
  &:hover {
    background: rgba(11, 43, 132, 0.8);
    border: 1px solid #00f6ff;
    box-shadow: inset 0 0 7px #00f6ff;
    color: #00f6ff;
  }

  &.disabled {
    color: #b4bfd3;
    background: rgba(21, 52, 120, 0.8);
    border: 1px solid #0987b9;
    pointer-events: none;
    box-shadow: none;
    // cursor: no-drop;
  }
}

.query-type-label {
  width: 100%;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  white-space: nowrap;
}

.center-time-text {
  position: absolute;
  z-index: 10;
  left: 50%;
  top: 118px;
  transform: translateX(-50%);
  font-size: 20px;
  font-family: "Microsoft YaHei", "Microsoft YaHei-Bold", serif;
  font-weight: 700;
  text-align: center;
  color: #00f6ff;
  line-height: 22px;
}
</style>
